<!--
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<!DOCTYPE html>
<html>
<head>
  <title>SuperCharged 💫</title>
  <link rel="stylesheet" type="text/css" href="main.css" />
  <meta charset="UTF-8" />
</head>
<body>
  <div>
    <input type="file" accept="image/*" name="input" id="input">
    <label for="input" >Choose File</label>
  </div>

  <canvas id="preview"></canvas>

  <script type="text/javascript">
    const $input = document.getElementById('input');
    const $preview = document.getElementById('preview');
    const previewCtx = $preview.getContext('2d');
    const worker = new Worker('worker.js');
    

    /** Sends image data to Worker to apply a filter. */
    function applyFilter() {
      const imageData = previewCtx.getImageData(0, 0, $preview.width, $preview.height);
      worker.postMessage(imageData, [imageData.data.buffer]);
    }


    /**
     * Listens messages from worker.
     * In this case: puts image data back to the canvas.
     * @param {!Object} d Data sent by the worker.
     */
    worker.addEventListener('message', (d) => {
      const imageData = d.data;
      previewCtx.putImageData(imageData, 0, 0);
    });


    /**
     * Processes image when added to input file. Including:
     *   1. Resizing and drawing image in cavas.
     *   2. Applying a filter (using a web worker).
     * @param {!Event} e On change event on the input file.
     */
    $input.addEventListener('change', (e) => {
      const file = e.target.files[0];

      /**
       * Creates an ImageBitmap from loaded map.
       * Once loaded: the image bitmap is added to canvas and a filter is applied.
       * @param {!ImageBitmap} bitmap of the image loaded on the input field.
       */
      createImageBitmap(file).then((bitmap) => {
          $preview.height = bitmap.height;
          $preview.width = bitmap.width;
          previewCtx.drawImage(bitmap, 0, 0);
          applyFilter();
      });
    });
  </script>
</body>
</html>
